package ru.arriah.servicedesk.web.dispatcher.action;

import java.io.IOException;
import java.util.Collection;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;


public class ProcessRequestFormAction extends DumbAction {
   protected RequestManagerLocalHome requestManagerHome;

   public ProcessRequestFormAction() throws NamingException {
      super();
      requestManagerHome =
         Utils.getRequestManagerHomeInterface();
   }

   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
     try {
       int userId = Utils.getUserId(request);
       
       RequestBean requestBean = new RequestBean();                      
       requestBean.setDispatcherText(request.getParameter("text"));
       requestBean.setOrganizationId(idVal(request.getParameter("organization_id")));
       requestBean.setDepartmentId(idVal(request.getParameter("department_id")));
       requestBean.setClientId(idVal(request.getParameter("client_id")));
       requestBean.setGroupId(idVal(request.getParameter("group_id")));
       requestBean.setRequestTypeId(idVal(request.getParameter("requesttype_id")));
       
       RequestManagerLocalObject requestManager = requestManagerHome.create();
              
       int requestId = idVal(request.getParameter("id"));
       if(requestId == 0) {
         requestManager.addRequest(requestBean, userId);
         
         addInfMessage(
            request,
            "request added"
         );
         
       } else {
         requestBean.setId(requestId);
         requestManager.updateRequest(requestBean, userId);
                  
         addInfMessage(
            request,
            "request Updated"
         );
       }
       
       Collection<RequestBean> requestsList = requestManager.selectRequestsByStatus(1);
       request.setAttribute("requestsList", requestsList);
       
       requestManager.remove();                                   
              
       return actionMapping.getSuccessTarget();
    } catch (Exception e) {
       handleException(e, "execute");
       throw new InternalException("ErrorMessage.internal");
    }
   }
}